/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.icybear.gae.pechapaii.service;

import com.google.appengine.repackaged.com.google.common.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
 *
 * @author Bearice
 */
public class CryptoService {

    private String key;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String encrypt(String in) throws Exception {
        try {
            Cipher cipher = init(Cipher.ENCRYPT_MODE);
            return Base64.encode(cipher.doFinal(in.getBytes()));
        } catch (Exception ex) {
            throw new Exception("fail to encrypt", ex);
        }
    }

    public String decrypt(String in) throws Exception {
        try {
            Cipher cipher = init(Cipher.DECRYPT_MODE);
            return new String(cipher.doFinal(Base64.decode(in)));
        } catch (Exception ex) {
            throw new Exception("fail to decrypt", ex);
        }
    }

    private Cipher init(int mode) throws Exception {
        byte[] salt = "CAFEBABE".getBytes();
        int count = 20;
        PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
        PBEKeySpec pbeKeySpec = new PBEKeySpec(key.toCharArray());
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(mode, pbeKey, pbeParamSpec);
        return pbeCipher;
    }

    public static void main(String... args) throws Exception {
        CryptoService c = new CryptoService();
        c.setKey("test");
        String text = "hello world";
        String enc = c.encrypt(text);
        String dec = c.decrypt(enc);
        System.out.println("encrypted:" + enc);
        System.out.println("decrypted:" + dec);
    }
}
